//
//  UIColor+Extension.m
//  TableDemo
//
//  Created by jutuo on 2020/3/25.
//  Copyright © 2020 jutuo. All rights reserved.
//

#import "UIColor+Extension.h"


@implementation UIColor (Extension)
// 随机获取一种颜色
+ (UIColor *)arc4randomColor
{
    return [UIColor colorWithRed:arc4random() % 255 / 255.0 green:arc4random() % 255 / 255.0  blue:arc4random() % 255 / 255.0  alpha:1];
}

// 16进制颜色,alpha = 1.0
+ (UIColor *)colorFormRGBHex:(unsigned int)hex
{
    return [self colorFormRGBHex:hex alpha:1.0];
}

// 16进制颜色,alpha范围 0~1
+ (UIColor *)colorFormRGBHex:(unsigned int)hex alpha:(float)alpha
{
    return [UIColor colorWithRed:((float)((hex & 0xFF0000) >> 16))/255.0 green:((float)((hex & 0xFF00) >> 8))/255.0 blue:((float)(hex & 0xFF))/255.0 alpha:alpha];
}

// 获取color, 取值在0~255，alpha 默认 1.0
+ (UIColor *)colorFormRed:(CGFloat)red green:(float)green blue:(float)blue
{
    return [self colorWithRed:red green:green blue:blue alpha:1.0];
}

// 获取color, 颜色值取值在0~255，alpha 范围 0~1
+ (UIColor *)colorFormRed:(CGFloat)red green:(float)green blue:(float)blue alpha:(float)alpha
{
    return [self colorWithRed:red / 255.0 green:green / 255.0 blue:blue / 255.0 alpha:alpha];
}

// 将16进制的颜色转换成color
+ (UIColor *)colorWithHexString:(NSString *)hexString
{
   return [UIColor colorWithHexString:hexString alpha:1];
}

// 将16进制的颜色转换成color
+ (UIColor *)colorWithHexString:(NSString *)hexString alpha:(CGFloat)alpha
{
    NSString *cString = [[hexString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    
    if ([cString length] < 6)
        return [UIColor whiteColor];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString hasPrefix:@"0x"] || [cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    if ([cString length] != 6)
        return [UIColor whiteColor];
    
    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString *rString = [cString substringWithRange:range];
    
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f)
                           green:((float) g / 255.0f)
                            blue:((float) b / 255.0f)
                           alpha:alpha];
}
@end
